// pages/detail/goods-detail-page.js

const util = require('../../util/util.js');
const app = getApp()
import { RequestManager } from '../../util/requestManager.js'

import {
  obj_category, obj_goods, obj_address, obj_coupon, obj_discountItem, obj_goodsDetail,
  obj_goodsOptionItem,
  obj_goodsIngredientsItem,
  obj_cartGoodsItem
} from '../../util/model.js'

let requestManager = new RequestManager()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    conentMarginTop: 0,
    isPhoneX:false,
    itemDetail: {},

    //  是否显示indicatorDots
    indicatorDots:true,  

    //  类型
    optionItems:Array(),
    didSelectedOptionItem:{},

    //  尺寸的大小
    isShowSize:false,
    itemSizeWidth:50,
    sizeItems:Array(),
    didSelectedSizeItem:{},

    //  购物车的动画效果
    animationCart:{},

    animationY: {},
    animationX: {},
    ballY: 0,
    ballX: 0,
    isLoading: false,
    showBall: false,

    itemAmount:'0.00',
    //  购物车数据
    totalAmount:'0.00',
    totalCount:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
      isPhoneX: app.globalData.isIphoneX,
      conentMarginTop: app.globalData.navHeight
    })

    var goodsId = options.goodsId;

    this.private_initAnimationData();
    this.private_downloadData(goodsId);
    this.private_computeCartData();
  },
  onShow:function(){
    var that = this;
    requestManager.getAllCartList(app.globalData.openid, result => {
      //  赋值给全局变量
      app.globalCart = result
      that.private_computeCartData();
    });
  },

  //  获取数据
  private_downloadData: function (goodsId) {
    
    var that = this;
    requestManager.getGoodsDetail(goodsId,res => {

      const sizeCount = res.sizeItems.length
      var screenWidth = app.globalData.screenW;

      var tmpSizeItem = res.sizeItems[0]
      var tmpOptionItem = res.optionItems[0]
      tmpOptionItem.show = true
      var tmpItemAmount = (res.price + tmpOptionItem.price + tmpSizeItem.price).toFixed(2)
      that.setData({
        itemDetail: res,
        isShowSize: sizeCount > 1 ? true : false,
        itemSizeWidth: ((screenWidth - 750/30) / sizeCount),
        didSelectedSizeItem: tmpSizeItem,
        sizeItems: res.sizeItems,
        didSelectedOptionItem: tmpOptionItem,
        optionItems: res.optionItems,
        indicatorDots: res.images.length > 1 ? true : false,
        itemAmount:tmpItemAmount
      })
    });
  },
  //  获取动画坐标数据
  private_initAnimationData:function(){

    var screenWidth = app.globalData.screenW;
    var screenHeight = app.globalData.screenH - app.globalData.safeArea_top - 65 + app.globalData.navHeight;

    this.setData({
      ballX: screenWidth / 2,
      ballY: screenHeight - (app.globalData.isIphoneX ? 49 : 15)
    });
  },
  //  统计购物车里的数据
  private_computeCartData:function(){
    var tmpCartItems = app.globalCart;
    var totalAmount = 0.00;
    tmpCartItems.forEach((tmpItem) => {
      totalAmount += parseFloat(tmpItem.price * tmpItem.count);
    })
    this.setData({
      totalAmount: totalAmount.toFixed(2),
      totalCount: tmpCartItems.length
    });
  },
  //  
  private_joinCartAnimation:function(callback){
    //加入购物车动画
    if (this.data.isLoading) {
      return;
    }

    //  加入购物车的动画效果
    let that = this,
      moveX = this.data.ballX,
      animationX = util.flyXAnimation(-moveX / 2.0),
      animationY = util.flyYAnimation(-60);

    that.setData({
      showBall: true,
      isLoading: true
    });

    util.setDelayTime(100).then(() => {
      that.setData({
        animationX: animationX.export(),
        animationY: animationY.export()
      });
      return util.setDelayTime(300);
    }).then(() => {
      that.setData({
        animationX: util.flyXAnimation(-(moveX - 20)).export(),
        animationY: util.flyYAnimation(0, 300, 'ease-in').export(),
      });
      return util.setDelayTime(300);
    }).then(() => {
      that.setData({
        animationX: util.flyXAnimation(0, 0).export(),
        animationY: util.flyYAnimation(0, 0).export(),
        showBall: false,
        animationCart: util.flyYAnimation(5, 200).export()
      })
      return util.setDelayTime(100);
    }).then(() => {
      that.setData({
        animationCart: util.flyYAnimation(0, 200).export(),
        isLoading: false,
      })
      return util.setDelayTime(200);
    }).then(() => {
      //  动画执行完，需要把数据加入购物车
      callback()
    });
  },
  //选项被点击是否显示
  action_optionDidShow: function (event) {

    var selectedItem = event.detail;
    var tmpOptionItems = this.data.optionItems;

    tmpOptionItems.forEach((tmpItem) => {

      if (tmpItem.id === selectedItem.id) {
        tmpItem.show = selectedItem.show;
        tmpItem.checked = true;
      }
      else {
        tmpItem.show = false;
        tmpItem.checked = false
      }
    })

    this.setData({
      optionItems:tmpOptionItems
    })

    this.action_optionDidSelected(event)
  },

  //选项是否会选择
  action_optionDidSelected: function (event){
    var selectedItem = event.detail;
    var tmpOptionItems = this.data.optionItems;

    var tmpOptionItem = tmpOptionItems[0]

    tmpOptionItems.forEach((tmpItem) => {
      if (tmpItem.id === selectedItem.id) {
        tmpItem.show = selectedItem.show;
        if (!tmpItem.checked){
          tmpItem.checked = selectedItem.checked;
          tmpItem.show = true
        }
      }
      else {
        tmpItem.show = false;
        tmpItem.checked = false;
      }

      if(tmpItem.checked){
        tmpOptionItem = tmpItem
      }
    })

    var tmpSizeItem = this.data.didSelectedSizeItem
    var tmpItemAmount = (this.data.itemDetail.price + tmpOptionItem.price + tmpSizeItem.price).toFixed(2)

    this.setData({
      optionItems: tmpOptionItems,
      didSelectedOptionItem: tmpOptionItem,
      itemAmount: tmpItemAmount
    })
  },

  //  选择尺寸大小
  action_sizeDidSelected:function(event){
    var selectedId = event.currentTarget.dataset.id
    var tmpSizeItems = this.data.sizeItems;
    var tmpSelectedSizeItem = null;
    tmpSizeItems.forEach((tmpItem)=>{
      tmpItem.isSelected = tmpItem.id == selectedId ? true :false
      if (tmpItem.isSelected) {
        tmpSelectedSizeItem = tmpItem
      }
    })

    var tmpOptionItem = this.data.didSelectedOptionItem
    var tmpItemAmount = (this.data.itemDetail.price + tmpOptionItem.price + tmpSelectedSizeItem.price).toFixed(2)
    this.setData({
      sizeItems: tmpSizeItems,
      didSelectedSizeItem: tmpSelectedSizeItem,
      itemAmount: tmpItemAmount
    })
  },
  //  跳转到购物车
  action_cart:function(event){
    // wx.switchTab({
    //   url: '/pages/cart/cart-page'
    // })
    wx.navigateTo({
      url: '/pages/detail/goods-detail-cart-page',
    })
  },
  
  //  加入购物车
  action_joinToCart:function(event){

    var tmpOptionItems = this.data.itemDetail.optionItems;
    //  选中的口味
    var isSelectedOptionItem = null
    tmpOptionItems.forEach((tmpItem)=>{
      if (tmpItem.checked){
        isSelectedOptionItem = tmpItem;
      }
    });

    if (!isSelectedOptionItem){
      wx.showToast({
        title: "请先选择需要购买的类型",
        icon: 'none'
      });
      return;
    }

    //  选中的尺寸
    var isSeleectedSizeItem = null
    this.data.itemDetail.sizeItems.forEach((tmpItem)=>{
      if(tmpItem.isSelected){
        isSeleectedSizeItem = tmpItem
      }
    })
    
    this.private_joinCartAnimation(()=>{

      //  加入购物车操作
      var tmpCartItems = app.globalCart;
      var tmpGoodItem = this.data.itemDetail;

      var ower = false;
      tmpCartItems.forEach((tmpItem) => {
        if (tmpItem.goodsItem.id === tmpGoodItem.id && tmpItem.optionItem.id === isSelectedOptionItem.id && tmpItem.sizeItem.id === isSeleectedSizeItem.id) {
          ower = true;
          tmpItem.count += 1
        }
      })
      if(!ower){
        var tmpItem = new obj_cartGoodsItem(tmpGoodItem, isSelectedOptionItem, isSeleectedSizeItem,1)
        tmpCartItems.push(tmpItem);
      }
      app.globalCart = tmpCartItems;

      var tmpItemDetail = this.data.itemDetail;
      var tmpOptionItems = tmpItemDetail.optionItems;

      tmpOptionItems.forEach((tmpItem,index) => {
        tmpItem.show = index == 0 ? true : false;
        tmpItem.checked = index == 0 ? true : false;
      })

      var tmpSizeItems = tmpItemDetail.sizeItems;
      tmpSizeItems.forEach((tmpItem,index)=>{
        tmpItem.isSelected = index == 0 ? true : false;
      })

      var tmpSizeItem = tmpItemDetail.sizeItems[0]
      var tmpOptionItem = tmpItemDetail.optionItems[0]
      var tmpItemAmount = (tmpItemDetail.price + tmpOptionItem.price + tmpSizeItem.price).toFixed(2)
      
      this.setData({
        sizeItems: tmpSizeItems,
        didSelectedSizeItem: tmpSizeItem,
        optionItems: tmpOptionItems,
        didSelectedOptionItem: tmpOptionItem,
        itemAmount: tmpItemAmount
      })
      //  网络请求---
      requestManager.addGoodsItemToCart(app.globalData.openid,tmpGoodItem.id,isSelectedOptionItem.id,isSeleectedSizeItem.id,res=>{

      })
      
      this.private_computeCartData();
    });
  },

  //  客服
  handleContact:function(event){
    console.log(event)
  }
})